﻿using System;
using System.Collections.Generic;
using System.Text;
using Wedn.Core.Common;
using Wedn.Core.Entity;
using Wedn.Core.Service;
using Wedn.Core.Utility;

namespace Wedn.TemplateEngine.UC
{
    /// <summary>
    /// 自定义母版页可以选择从此类派生, 从而获得数据 在需要调用数据时直接调用方法名(例如:"<%=GetTitle()%>")
    /// 如果使用系统默认的CodeBehind技术, 则必须在方法名前面加上类名. (例如:"<%=(MasterFun.GetTitle())%>")
    /// </summary>
    public class Master : System.Web.UI.MasterPage
    {
        private IDictionary<string, object> dict;
        /// <summary>
        /// 初始化标签字典
        /// </summary>
        public void SetDict(IDictionary<string, object> dict)
        {
            this.dict = dict;
        }
        /// <summary>
        /// 增加一对键值对
        /// </summary>
        /// <param name="kv">键值对</param>
        public void SetDict(KeyValuePair<string, object> kv)
        {
            if (!dict.Keys.Contains(kv.Key))
            {
                this.dict.Add(kv);
                return;
            }
            else
            {
                this.dict[kv.Key] = kv.Value;
            }
        }
        /// <summary>
        /// 数据字典索引器
        /// </summary>
        /// <param name="index">索引</param>
        /// <returns>值</returns>
        public object this[string index]
        {
            get
            {
                string temp = index.ToLower();
                if (dict.Keys.Contains(temp))
                {
                    return dict[temp];
                }
                return null;
            }
        }
        /// <summary>
        /// 获取跟站点有关信息数据, 返回查询到的字符串, 如果不存在则返回null
        /// </summary>
        /// <param name="key">指定查选的名称, 参照说明</param>
        /// <returns>查询到的字符串, 如果不存在则返回null</returns>
        public string SiteInfo(string key)
        {
            return dict[key.ToLower()].ToString();
        }
        /// <summary>
        /// 计算页面加载时间
        /// </summary>
        /// <param name="dt">开始时间,传入(index.Starttick)即可</param>
        /// <returns>页面加载时间(s)</returns>
        public string GetLoadTime(DateTime dt)
        {
            return Convert.ToString(DateTime.Now.Subtract(dt).TotalMilliseconds / 1000);
        }
        /// <summary>
        /// 统计页面执行查询次数
        /// </summary>
        public int Queries
        {
            get
            {
                int n = QueryInfo.QueryCount;
                QueryInfo.QueryCount = 0;
                return n;
            }
        }
        /// <summary>
        /// 统计页面执行时间
        /// </summary>
        public string ExecTime
        {
            get
            {
                return Convert.ToString(DateTime.Now.Subtract(QueryInfo.ExecuteTime).TotalMilliseconds / 1000);
            }
        }
        /// <summary>
        /// 是否为文章页
        /// </summary>
        public bool IsPostPage
        {
            get { return RequestHelper.QueryType == PageType.Post; }
        }

        #region 模版操作

        /// <summary>
        /// 加载模板
        /// </summary>
        public void Include()
        {
            string pageType = RequestHelper.QueryType.ToString().ToLower();
            string templateName = Config.TemplateRule[pageType];
            string templatePath = string.Format("{0}themes/{1}/templates/{2}.ascx", Config.SiteRoot, Setting.Theme, templateName);
            TemplateHelper th = new TemplateHelper();
            th.Load(templatePath);
            th.Set((Dictionary<string, object>)dict);
            th.Render(Response.Output);
        }

        /// <summary>
        /// 根据模版文件名加载模板
        /// </summary>
        /// <param name="templateName">模版文件名</param>
        public void Include(string templateName)
        {
            TemplateHelper th = new TemplateHelper();
            th.Load(string.Format("/themes/{0}/templates/{1}", Setting.Dict["Theme"].ToString(), templateName));
            th.Set((Dictionary<string, object>)dict);
            th.Render(Response.Output);
        }

        #endregion

        #region 加载导航菜单(已优化)

        List<Link> navs = null;
        /// <summary>
        /// 加载导航栏
        /// </summary>
        /// <returns>导航栏HTML块</returns>
        public string LoadNav()
        {
            LinkManager linkManager = new LinkManager();
            if (navs == null)
            {
                navs = linkManager.GetLinkList(LinkType.Navigation, true);
            }
            List<Link> list = navs.FindAll(x => x.ParentId == 0);
            if (list.Count == 0)
                return string.Empty;
            StringBuilder sbd = new StringBuilder("<ul id=\"nav\" class=\"menu\">");
            foreach (var item in list)
            {
                if (item.ParentId == 0)
                {
                    sbd.Append(string.Format("<li><a href=\"{0}\" title=\"{1}\" target=\"{2}\">{3}</a>", item.Url, item.Title, item.Target, item.Name));
                    LoadNav(sbd, item);
                }
            }
            sbd.Append("</ul>");
            return sbd.ToString();
        }
        /// <summary>
        /// 递归加载子菜单
        /// </summary>
        /// <param name="sbd"></param>
        /// <param name="item"></param>
        private void LoadNav(StringBuilder sbd, Link item)
        {
            List<Link> subList = navs.FindAll(x => x.ParentId == item.Id);
            if (subList.Count == 0)
                return;
            sbd.Append("<ul style=\"display: none;\">");
            foreach (var subItem in subList)
            {
                sbd.Append(string.Format("<li><a href=\"{0}\" title=\"{1}\" target=\"{2}\">{3}</a>", subItem.Url, subItem.Title, subItem.Target, subItem.Name));
                LoadNav(sbd, subItem);
                sbd.Append("</li>");
            }
            sbd.Append("</ul>");
            sbd.Append("</li>");
        }

        #endregion
    }
    #region 老版本
    //public class Master : System.Web.UI.MasterPage
    //{
    //    private IDictionary<string, object> dict = new Dictionary<string, object>();
    //    /// <summary>
    //    /// 数据字典
    //    /// </summary>
    //    public IDictionary<string, object> Dict
    //    {
    //        get { return dict; }
    //        set { dict = value; }
    //    }
    //    /// <summary>
    //    /// 数据字典索引器
    //    /// </summary>
    //    /// <param name="index">索引</param>
    //    /// <returns>值</returns>
    //    public object this[string index]
    //    {
    //        get
    //        {
    //            if (dict.Keys.Contains(index))
    //            {
    //                return dict[index];
    //            }
    //            else
    //            {
    //                return null;
    //            }
    //        }
    //    }

    //    /// <summary>
    //    /// 是否为文章页
    //    /// </summary>
    //    public bool IsPostPage
    //    {
    //        get { return RequestHelper.QueryString("type", true) == "post"; }
    //    }

    //    /// <summary>
    //    /// 加载模板
    //    /// </summary>
    //    public new void Include(string templateName)
    //    {
    //        TemplateHelper th = new TemplateHelper();
    //        th.Load(string.Format("/themes/{0}/template/{1}", OptionManager.Settings["Theme"].ToString(), templateName));
    //        th.Display(Response.Output);
    //    }

    //    /// <summary>
    //    /// 加载导航栏
    //    /// </summary>
    //    /// <returns>导航栏HTML块</returns>
    //    public string LoadNav()
    //    {
    //        StringBuilder sbd = new StringBuilder("<ul id=\"nav\" class=\"menu\">");
    //        List<Link> list = LinkManager.GetLinkList(0, "navigation", true);
    //        foreach (var item in list)
    //        {
    //            if (item.ParentId == 0)
    //            {
    //                sbd.Append(string.Format("<li><a href=\"{0}\" title=\"{1}\" target=\"{2}\">{3}</a>", item.Url, item.Title, item.Target, item.Name));
    //                LoadNav(sbd, item);
    //            }
    //        }
    //        sbd.Append("</ul>");
    //        return sbd.ToString();
    //    }

    //    /// <summary>
    //    /// 递归加载子菜单
    //    /// </summary>
    //    /// <param name="sbd"></param>
    //    /// <param name="item"></param>
    //    private void LoadNav(StringBuilder sbd, Link item)
    //    {
    //        List<Link> subList = LinkManager.GetLinkList(item.Id, "navigation", true);
    //        if (subList.Count != 0)
    //        {
    //            sbd.Append("<ul style=\"display: none;\">");
    //            foreach (var subItem in subList)
    //            {
    //                sbd.Append(string.Format("<li><a href=\"{0}\" title=\"{1}\" target=\"{2}\">{3}</a>", subItem.Url, subItem.Title, subItem.Target, subItem.Name));
    //                LoadNav(sbd, subItem);
    //            }
    //            sbd.Append("</ul>");
    //        }
    //        sbd.Append("</li>");
    //    }

    //    /// <summary>
    //    /// 计算页面加载时间
    //    /// </summary>
    //    /// <param name="dt">开始时间,传入(index.starttick)即可</param>
    //    /// <returns></returns>
    //    public string GetLoadTime(DateTime dt)
    //    {
    //        return Convert.ToString(DateTime.Now.Subtract(dt).TotalMilliseconds / 1000);
    //    }

    //    /// <summary>
    //    /// 统计页面执行查询次数
    //    /// </summary>
    //    public int Queries
    //    {
    //        get
    //        {
    //            int n = QueryInfo.QueryCount;
    //            QueryInfo.QueryCount = 0;
    //            return n;
    //        }
    //    }
    //} 
    #endregion
}
